#include "ExitLayer.h"
#include "ConstClass.h"
#include "StartLayer.h"
#include "AudioManage.h"

#define PNG_EXIT_BACK "Tip/exit_back.png"
#define PNG_OK "Tip/ok.png"
#define PNG_CANCEL "Tip/cancel.png"

ExitLayer::ExitLayer()
{
}


ExitLayer::~ExitLayer()
{
}

bool ExitLayer::init()
{
	Layer::init();

	BackColor == nullptr;

	Sprite* exit = Sprite::create(PNG_EXIT_BACK);
	exit->setPosition(Vec2::ZERO);
	this->addChild(exit, 10);

	MenuItemImage* okItem = MenuItemImage::create(PNG_OK, PNG_OK, CC_CALLBACK_0(ExitLayer::Exit, this));
	okItem->setPosition(Vec2(50, -50));
	MenuItemImage* cancelItem = MenuItemImage::create(PNG_CANCEL, PNG_CANCEL, CC_CALLBACK_0(ExitLayer::Back, this));
	cancelItem->setPosition(Vec2(100, -50));

	Menu* exitMenu = Menu::create(okItem, cancelItem, NULL);
	exitMenu->setPosition(Vec2::ZERO);

	this->addChild(exitMenu, 11);

	auto listener1 = EventListenerTouchOneByOne::create();
	listener1->setSwallowTouches(true);
	listener1->onTouchBegan = CC_CALLBACK_0(ExitLayer::callBack, this);

	_eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, this);
	_listener = listener1;

	return true;
}

void ExitLayer::onEnter()
{
	ConstClass::exiting = true;

	Layer::onEnter();

	if (BackColor == nullptr)
	{
		LayerColor* layerColor = LayerColor::create(cocos2d::Color4B(225, 225, 225, 100));
		this->getParent()->addChild(layerColor, 5);
		BackColor = layerColor;
	}
}

void ExitLayer::Exit()
{
	if (ConstClass::COM_GAME)
	{
		ConstClass::exiting = false;

		AudioManage::stopPlayMusic();
		AudioManage::stopStartMusic();

		auto director = Director::getInstance();
		Scene* startLayer = StartLayer::createScene();

		director->replaceScene(startLayer);
	}
}

void ExitLayer::Back()
{
	ConstClass::exiting = false;

	BackColor->setVisible(false);

	this->setVisible(false);
	_eventDispatcher->removeEventListener(_listener);
}

bool ExitLayer::callBack()
{
	log("callBack...");
	return true;
}

void ExitLayer::showExitLayer()
{
	ConstClass::exiting = true;

	BackColor->setVisible(true);

	auto listener1 = EventListenerTouchOneByOne::create();
	listener1->setSwallowTouches(true);
	listener1->onTouchBegan = CC_CALLBACK_0(ExitLayer::callBack, this);

	_eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, this);
	_listener = listener1;
}